package com.fulihui.information.service;

import com.fulihui.information.api.SourceService;
import com.fulihui.information.core.repository.SourceRepository;
import com.fulihui.information.dto.SourceDTO;
import com.fulihui.information.enums.ESourceStatus;
import com.fulihui.information.request.SourceQueryRequest;
import com.fulihui.information.request.SourceStatusRequest;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.Errors;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TPageResult;
import org.near.servicesupport.util.ServiceAssert;
import org.near.toolkit.common.EnumUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.near.servicesupport.result.ResultBuilder.succ;

/**
 *
 * Created by LeeSon on 2017/1/16 0016.
 */
@Service(version = "1.0.0")
public class SourceServiceImpl implements SourceService {
    @Autowired
    private SourceRepository sourceRepository;

    @Override
    public BaseResult modifyStatus(SourceStatusRequest request) {
        ServiceAssert.isTrue(EnumUtil.inEnum(request.getStatus(), ESourceStatus.class),
            Errors.Commons.REQUEST_PARAMETER_ERROR);

        boolean addDislike = sourceRepository.modifyStatus(request.getSourceId(),
            request.getStatus());
        ServiceAssert.isTrue(addDislike, Errors.Commons.SYSTEM_ERROR);

        return succ();
    }

    @Override
    public TPageResult<SourceDTO> queryPage(SourceQueryRequest request) {
        String status = request.getStatus();
        if (isNotEmpty(status)) {
            ServiceAssert.isTrue(EnumUtil.inEnum(status, ESourceStatus.class),
                Errors.Commons.REQUEST_PARAMETER_ERROR);
        }

        List<SourceDTO> sourceDTOList = sourceRepository.queryPage(request);
        int queryPageCount = sourceRepository.queryPageCount(request);
        return ResultBuilder.succTPage(sourceDTOList, request.getPage(), request.getRows(),
            queryPageCount);
    }
}